<template>
    <div class="user-manage">
        <div class="query-form">
            <el-form ref="userFormRef" inline :model="userForm">
                <el-form-item label="用户ID:" prop="userId">
                    <el-input v-model="userForm.userId" placeholder="请输入用户ID"></el-input>
                </el-form-item>
                <el-form-item label="用户名称:" prop="userName">
                    <el-input v-model="userForm.userName" placeholder="请输入用户名"></el-input>
                </el-form-item>
                <el-form-item label="状态:" prop="state">
                    <el-select v-model="userForm.state">
                        <el-option :value="0" label="所有"></el-option>
                        <el-option :value="1" :label="STATE[1]"></el-option>
                        <el-option :value="2" :label="STATE[2]"></el-option>
                        <el-option :value="3" :label="STATE[3]"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button @click="search" type="primary">查询</el-button>
                    <el-button @click="reset">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="base-table">
            <div class="action">
                <el-button @click="add" v-HasPermission="'user-create'" type="primary">新增</el-button>
                <el-button type="danger" v-HasPermission="'user-patch-delete'" @click="batchRemove()">批量删除</el-button>
            </div>
            <el-table @selection-change="handleSelect" :data="tableData.data" style="width:100%;">
                <el-table-column type="selection" width="55" />
                <el-table-column v-for="item in tableData.columns" :key="item.prop" :prop="item.prop"
                    :label="item.label" :width="item.width">
                    <template #default="scope" v-if="item.render">
                        <span>{{item.render ? item.render(scope.row,scope.column) : ''}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200" align="center">
                    <template #default="scope">
                        <el-button @click="edit(scope.row)" v-HasPermission="'user-edit'">编辑</el-button>
                        <el-button type="danger" v-HasPermission="'user-delete'" @click="singleRemove(scope.row)">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <Pagination :page="tableData.page" @change-size="changeSize" />
        </div>
        <!-- 编辑和新增 -->
        <user-edit-form :type="action" :userFormData="formData.userFormData" :show="show" :title="formData.title"
            @close="close" @submit="submit"></user-edit-form>
    </div>
</template>

<script setup lang='ts'>
import { ref, reactive, onMounted, PropType } from 'vue'
import { User, UserForm, UserListParams } from "@/interface/user"
import { Columns } from "@/interface/common"
import { STATE, ROLE } from "@/utils/enum"
import type { FormInstance } from 'element-plus'
import { userList, deleteUser, userCreate, userEdit } from "@/api/user"
import Pagination from "@/components/Pagination.vue"
import useCurrentInstance from "@/hook/useCurrentInstance"
import userEditForm from "./component/userForm.vue"
import utils from "@/utils/utils.js"

// 表单实例
const userFormRef = ref<FormInstance>()
// 查询参数
const userForm = reactive<User>({
    userId: '',
    userName: "",
    state: 0
})
// 查询用户列表
const search = () => {
    console.log("查询")
    tableData.page!.pageNum = 1
    getUserList()
}
// 重置搜索
const reset = () => {
    console.log('重置搜索', userFormRef.value)
    userFormRef!.value?.resetFields()
}

// 表格对象
const tableData = reactive<Columns>({
    data: [],
    columns: [
        {
            label: '用户ID',
            prop: "userId"
        },
        {
            label: "用户名",
            prop: "userName"
        },
        {
            label: '用户角色',
            prop: "role",
            render: (row, column) => {
                const { role } = row
                return ROLE[role]
            }
        },
        {
            label: "用户状态",
            prop: 'state',
            render: (row, column) => {
                const { state } = row
                return STATE[state]
            }
        },
        {
            label: '注册时间',
            prop: 'createTime',
            render: (row, column) => {
                return utils.formateDate(new Date(row.createTime))
            }
        },
        {
            label: '最后登录时间',
            prop: 'lastLoginTime',
            render: (row, column) => {
                return utils.formateDate(new Date(row.lastLoginTime))
            }
        }
    ],
    page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
    }
})
// 获取用户列表
const getUserList = async () => {
    let params = { ...userForm, ...tableData.page } as UserListParams
    try {
        const { list, page } = await userList(params)
        console.log("用户列表数据", list)
        console.log("用户分页数据", page)
        tableData.data = list
        tableData.page = page
    } catch (err) {
        console.error(err)
    }
}
onMounted(() => {
    getUserList()
})
// 获取多选的id数组
const checkedUserIds = ref<number[]>([])
// 获得选中用户
const handleSelect = (selection: any) => {
    console.log("选中的数据", selection)
    checkedUserIds.value = []
    for (let { userId } of selection) {
        checkedUserIds.value.push(userId)
    }
    console.log(checkedUserIds.value)
}
const batchRemove = async () => {
    if (checkedUserIds.value.length === 0) {
        that.$message.error("请选择要删除的用户")
        return
    }
    const { nModified } = await deleteUser({ userId: checkedUserIds.value })
    if (nModified > 0) {
        that.$message.success("删除成功!")
        getUserList()
    } else {
        that.$message.success("删除失败!")
    }
}
// 页码变化
const changeSize = (num: number) => {
    tableData.page!.pageNum = num
    getUserList()
}

const add = () => {
    action.value = "add"
    formData.title = "用户新增"
    show.value = true
}
const { globalProperties: that } = useCurrentInstance()
const singleRemove = async (row: any) => {
    console.log("数据", row)
    const { userId } = row
    const { nModified } = await deleteUser({ userId: [userId] })
    if (nModified > 0) {
        that.$message.success("删除成功!")
        getUserList()
    } else {
        that.$message.success("删除失败!")
    }
}

const edit = (row: UserForm) => {
    console.log("该行数据", row)
    action.value = "edit"
    formData.title = "用户编辑"
    show.value = true
    formData.userFormData = Object.assign({}, row, { userId: row.userId })
}
// 弹出框数据
const show = ref(false)
// 判断是编辑还是新增
const action = ref('add')
const formData = reactive({
    title: '',
    userFormData: {}
})
const close = () => {
    console.log("关闭弹出框")
    show.value = false
    action.value = ""
}
const submit = async (data: UserForm) => {
    console.log("提交表单内容", data)
    if (action.value === 'add') {
        const res = await userCreate({ ...data })
        if (res) {
            show.value = false
            that.$message.success("用户创建成功")
            getUserList()
        }
        return
    }

    console.log("编辑的数据", data)
    const res = await userEdit({ ...data })
    if (res) {
        that.$message.success("用户编辑成功")
        getUserList()
    }

}
</script>

<style lang='scss' scoped>
.user-manage {
    width: 100%;
}
</style>